﻿using CommonUtility;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Xml;

namespace WPay.Infrastructure.Unity
{
    /// <summary>
    /// Http请求帮助类
    /// </summary>
    public class HttpHelper
    {
        /// <summary>
        /// HttpGet
        /// </summary>
        /// <param name="sParams"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public static T HttpGet<T>(SortedDictionary<string, string> sParams, string Url)
        {
            var retString = "";
            var url = "";
            try
            {
               
                
                //发送请求
                var reqParamString = sParams.Keys.Aggregate(string.Empty, (current, key) => current + $"{key}={HttpUtility.UrlEncode(sParams[key])}&");
                reqParamString = reqParamString.TrimEnd('&');
                url = Url + "?" + reqParamString;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + "?" + reqParamString);
                //request.Timeout = 1000 * 60 * 3;
                request.Method = "GET";




                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                retString = myStreamReader.ReadToEnd();

                var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(retString);

                return obj;
            }
            catch (Exception e)
            {
                LoggerHelper.Log(e.Message + Newtonsoft.Json.JsonConvert.SerializeObject(e.InnerException) + "====" + url + retString);
                return default;
            }

        }
        /// <summary>
        /// 支付对账使用
        /// </summary>
        /// <param name="sParams"></param>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static string HttpGetString(SortedDictionary<string, string> sParams, string Url)
        {
            var retString = "";
            var url = "";
            try
            {

                //发送请求
                var reqParamString = sParams.Keys.Aggregate(string.Empty, (current, key) => current + $"{key}={HttpUtility.UrlEncode(sParams[key])}&");
                reqParamString = reqParamString.TrimEnd('&');
                url = Url + "?" + reqParamString;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + "?" + reqParamString);
                request.Method = "GET";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                retString = myStreamReader.ReadToEnd();
                return retString;
            }
            catch (Exception e)
            {
                LoggerHelper.Log("HttpGetString异常：" + e.Message + Newtonsoft.Json.JsonConvert.SerializeObject(e.InnerException) + "====" + url + retString);
                return default;
            }

        }
        public static string HttpGetString(string Url)
        {
            var retString = "";
            var url = "";
            try
            {

                //发送请求
                //var reqParamString = sParams.Keys.Aggregate(string.Empty, (current, key) => current + $"{key}={HttpUtility.UrlEncode(sParams[key])}&");
                //reqParamString = reqParamString.TrimEnd('&');
                //url = Url + "?" + reqParamString;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "GET";
                request.Headers.Add("Cookie", "__cdY3Jvbi5xcWUyLmNvbQ===1; .AspNetCore.Cookies=CfDJ8J_3z2cqYXpEveSDqs8soWiFM1D_yKjLkWik3ZLSwRpPapTIvCRk3wMl0-_on5AD6Pm0F_JU65Dre143JVP9SwHzXBcf70WqEb7lmCvYw2PiZ0wIgCcFa91ssAOyQPBWzm5JGpML222M2vTAoR0Su_U5hxADVr1kO6z1eiqkhem9kTXTiDlJ1SQt2pku3B36snWuh8m_KkdKhWldPtYyEscQ5PdS0Xbg14UTeG8zEZQxj7t1V8nGPQuv-AuM2JkvFsnJ5SQwIVT-9mhbBV6uxh4Eo8hZCSiv21bf27NuhR9vn2kT9NcKniH3bmG9vv6rXv1c2UUVBwssyPhshj77iiEhbYU77t_cAUeqpGvgqKfaIq0wfaBrDcTN2B5nm-QHk5jtUjTPiFrCdaRU3kR67wU");
                request.Timeout = 60 * 1000;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                retString = myStreamReader.ReadToEnd();
                return retString;
            }
            catch (Exception e)
            {
                LoggerHelper.Log("HttpGetString异常：" + e.Message + Newtonsoft.Json.JsonConvert.SerializeObject(e.InnerException) + "====" + url + retString);
                return default;
            }

        }
        /// <summary>
        /// HttpGet
        /// </summary>
        /// <param name="sParams"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public static string HttpGet(SortedDictionary<string, string> sParams, string method = "Inquire")
        {
            try
            {
                var Url = $"{ConfigManage.GetConfigByKey("OnliePay")}/{method}?";
                //发送请求
                var reqParamString = sParams.Keys.Aggregate(string.Empty, (current, key) => current + $"{key}={HttpUtility.UrlEncode(sParams[key])}&");
                reqParamString = reqParamString.TrimEnd('&');
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + reqParamString);
                request.Method = "GET";
                request.ContentType = "application/x-www-form-urlencoded";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(retString);
                return xmlDocument.InnerText;
            }
            catch (Exception e)
            {
                string exStr = "<WU_ROOT><BODY><HEAD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">"
                                          + $"<TYPE>REMOTEACCESS</TYPE><CODE>200</CODE><TITLE>系统错误</TITLE><MESSAGE>{e.Message}{e.InnerException?.Message}</MESSAGE>"
                                          + "</HEAD></BODY></WU_ROOT>";
                return exStr;
            }

        }


        public static string HttpGet2(string Url, string parms)
        {
            try
            {

                System.GC.Collect();
                System.Net.ServicePointManager.DefaultConnectionLimit = 10;
                byte[] data = Encoding.UTF8.GetBytes(parms);//参数
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                request.ContentType = "application/json";//表单提交

                request.ContentLength = data.Length;
                request.Timeout = 25 * 1000;
                request.KeepAlive = false;
                request.Proxy = null;
                Stream myRequestStream = request.GetRequestStream();
                StreamWriter myStreamWriter = new StreamWriter(myRequestStream);
                myStreamWriter.Write(parms);
                myStreamWriter.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
                if (request != null)
                {
                    request.Abort();
                    request = null;
                }
                return retString;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        /// <summary>
        /// 普通POST请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static String HttpPost(string url, IDictionary<string, string> parameters)
        {

            try
            {
                string strURL = url;
                HttpWebRequest request;
                request = (HttpWebRequest)WebRequest.Create(strURL);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.Timeout = 1000 * 30;//超时时间设置为30秒
                string paraUrlCoded = string.Join("&", parameters.Select(p => $"{p.Key}={p.Value}"));
                byte[] payload;
                payload = Encoding.UTF8.GetBytes(paraUrlCoded);
                request.ContentLength = payload.Length;
                Stream writer = request.GetRequestStream();
                writer.Write(payload, 0, payload.Length);
                writer.Close();
                writer.Dispose();
                HttpWebResponse response;
                response = (HttpWebResponse)request.GetResponse();
                Stream s;
                s = response.GetResponseStream();
                string StrDate = "";
                string strValue = "";
                using (StreamReader Reader = new StreamReader(s, Encoding.UTF8))
                {
                    while ((StrDate = Reader.ReadLine()) != null)
                    {
                        strValue += StrDate;
                    }
                }
                return strValue;

            }
            catch (Exception e)
            {

                return e.Message;
            }
        }
        /// <summary>
        /// 支付测试请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static String HttpPostPay(string url, IDictionary<string, string> parameters)
        {

            string strURL = url;
            HttpWebRequest request;
            request = (HttpWebRequest)WebRequest.Create(strURL);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Timeout = 20 * 1000;
            string paraUrlCoded = string.Join("&", parameters.Select(p => $"{p.Key}={p.Value}"));
            byte[] payload;
            payload = Encoding.UTF8.GetBytes(paraUrlCoded);
            request.ContentLength = payload.Length;
            Stream writer = request.GetRequestStream();
            writer.Write(payload, 0, payload.Length);
            writer.Close();
            writer.Dispose();
            HttpWebResponse response;
            response = (HttpWebResponse)request.GetResponse();
            Stream s;
            s = response.GetResponseStream();
            string StrDate = "";
            string strValue = "";
            using (StreamReader Reader = new StreamReader(s, Encoding.UTF8))
            {
                while ((StrDate = Reader.ReadLine()) != null)
                {
                    strValue += StrDate;
                }
            }
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(strValue);
            return xmlDocument.InnerText;
        }

        /// <summary>
        /// 发送消息机器人
        /// </summary>
        /// <param name="url"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static string PostERRORtOrOOT(string url, string msg)
        {
            try
            {
                System.GC.Collect();
                System.Net.ServicePointManager.DefaultConnectionLimit = 10;
                byte[] data = Encoding.UTF8.GetBytes(msg);//参数
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/json";//表单提交

                request.ContentLength = data.Length;
                request.Timeout = 25 * 1000;
                request.KeepAlive = false;
                request.Proxy = null;
                Stream myRequestStream = request.GetRequestStream();
                StreamWriter myStreamWriter = new StreamWriter(myRequestStream);
                myStreamWriter.Write(msg);
                myStreamWriter.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
                if (request != null)
                {
                    request.Abort();
                    request = null;
                }
                return retString;
            }
            catch (Exception e)
            {

                return "";
            }
        }
    }
}
